import React, { ReactNode } from 'react'
import say_love from '../component/random_message'
import store, { StoreContext } from '../store/store'
import './login.scss'
import _ from 'lodash'
import {initial as initializeGitDB} from 'gitee-simple-db'
import { initialize } from '../initial'
console.log(`Initial:`, initializeGitDB)

interface IProps {
    [propName: string]: string
}
interface IState {
    loveWords: string,
    loginHeight: {
        height: number
    },
    nickName: string,
    accessToken: string,
    [keyName: string]: any
}
export default class Login extends React.Component<IProps, IState> {
    // static contextType = 
    constructor(props: IProps) {
        super(props)
        this.state = {
            loveWords: "",
            loginHeight: {
                height: window.innerHeight
            },
            // @ts-ignore
            nickName: NICK_NAME || "",
            // @ts-ignore
            accessToken: ACCESS_TOKEN || "",
        }
        // say_love().then(word => this.setState({loveWords: word}))
    }
    componentDidMount() {
        console.log('did mount only called once.')
    }
    doLogin = () => {
        let {nickName, accessToken} = this.state;
        if (!_.isEmpty(nickName) && !_.isEmpty(accessToken)) {
            alert(`${nickName} login with ${accessToken}`)
            initialize({nickName, accessToken})
                .then(() => {
                    this.context.setLogined(true)
                    this.context.setStore(store)
                })
                .catch(e => {
                    console.error(e);
                    alert("登录异常" + e.message)
                })
        } else {
            alert("please input info")
        }
    }
    getInput = (e: any) => {
        // console.log('changed!')
        const target = e.target;
        const name = target.name;
        this.setState({
            [name]: target.value
        })
    }
    render():ReactNode {
        return (
            <div className="login-container" style={this.state.loginHeight}>
                <div className="login-zone">
                    <input className="login-input my-input" name="nickName" value={this.state.nickName} onChange={this.getInput} placeholder="请输入昵称"/>
                    <input className="login-input my-input" name="accessToken" value={this.state.accessToken} onChange={this.getInput} placeholder="请输入密钥"/>
                    <div className="st-btn login-btn" onClick={this.doLogin}>登 录</div>
                </div>
            </div>
        )
    }
}
Login.contextType = StoreContext